package com.example.beijing.beijingdemo.base;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.beijing.beijingdemo.R;
import com.example.beijing.beijingdemo.adapter.SwitchImageVPAdapter;
import com.example.beijing.beijingdemo.bean.NewsCenterTabBean;
import com.example.beijing.beijingdemo.util.MyLogger;
import com.example.beijing.beijingdemo.util.MyToast;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 新闻中心的Tab页面: 北京,中国,国际...
 */

public class NewsCenterTabPager implements ViewPager.OnPageChangeListener {

    private Context mContext;

    /**
     * 控件
     */
    public View view;
    private ViewPager mViewPager;
    private TextView mTvTitle;
    private LinearLayout mContainerPoints;
    private RecyclerView mRecyclerView;

    // 数据
    private NewsCenterTabBean newsCenterTabBean;

    // 轮播图的图片
    private List<ImageView> imageViews;

    // 用于自动轮播的Handler(消息机制)
    private Handler mHandler = new Handler();
    // 判断是否在切换
    private boolean hasSwitch;

    /**
     * 切换的任务
     */
    private class SwitchTack implements Runnable {
        @Override
        public void run() {
            // 切换逻辑
            int currentItem = mViewPager.getCurrentItem();
            // 是否到了最后一页
            if (currentItem == newsCenterTabBean.data.topnews.size() - 1) {
                currentItem = 0;
            } else {
                currentItem++;
            }
            mViewPager.setCurrentItem(currentItem);
            mHandler.postDelayed(this, 3000);
        }
    }

    /**
     * 开始切换
     */
    public void startSwitch() {
        if (!hasSwitch) {
            // 往Handler里面的消息队列里面,发送一个延时的消息
            mHandler.postDelayed(new SwitchTack(), 3000);
        }
    }

    /**
     * 停止切换
     */
    public void stopSwitch() {
//        mHandler.removeCallbacks(null);
        // 清空消息队列
        mHandler.removeCallbacksAndMessages(null);
        hasSwitch = false;
    }

    /**
     * 构造函数
     */
    public NewsCenterTabPager(Context mContext) {
        this.mContext = mContext;
        view = initView();
    }

    /**
     * 加载布局
     */
    private View initView() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.newscenter_content_tab, null);

        mViewPager = (ViewPager) view.findViewById(R.id.newscenter_content_tab_viewpager);
        mTvTitle = (TextView) view.findViewById(R.id.newscenter_content_tab_title);
        mContainerPoints = (LinearLayout) view.findViewById(R.id.newscenter_content_tab_points_container);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.newscenter_content_tab_recycleview);

        return view;
    }

    /**
     * 加载网络数据
     */
    public void loadNetData(String url) {
        OkHttpUtils.get()
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyToast.show(mContext, "加载数据失败");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        processData(response);
                    }
                });
    }

    /**
     * 处理Json数据
     */
    private void processData(String json) {
        MyLogger.e("data", json);
        Gson gson = new Gson();
        newsCenterTabBean = gson.fromJson(json, NewsCenterTabBean.class);

        // 把数据绑定给控件
        bindDataToView();
    }

    /**
     * 给控件绑定数据
     */
    private void bindDataToView() {
        // 加载轮播图片
        initSwitchImageView();
        // 加载轮播图的点
        initPoint();
    }

    /**
     * 初始化轮播图的点
     */
    private void initPoint() {
        // 清空所有的点
        mContainerPoints.removeAllViews();
        for (int i = 0; i < newsCenterTabBean.data.topnews.size(); i++) {
            View view = new View(mContext);
            // 设置背景
            view.setBackgroundResource(R.drawable.guide_point_grey);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(30, 30);
            // 左边距
            params.leftMargin = 50;
            mContainerPoints.addView(view, params);
        }
        // 让第一个点的背景为红
        mContainerPoints.getChildAt(0).setBackgroundResource(R.drawable.guide_point_red);
    }

    /**
     * 初始化轮播图的图片
     */
    private void initSwitchImageView() {
        imageViews = new ArrayList<>();
        for (int i = 0; i < newsCenterTabBean.data.topnews.size(); i++) {
            NewsCenterTabBean.TopNewsBean topNewsBean = newsCenterTabBean.data.topnews.get(i);
            ImageView iv = new ImageView(mContext);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            // 加载网络图片
            Picasso.with(mContext).load(topNewsBean.topimage).into(iv);
            imageViews.add(iv);
        }

        // 设置设配器
        SwitchImageVPAdapter vpAdapter = new SwitchImageVPAdapter(imageViews);
        mViewPager.setAdapter(vpAdapter);

        // 设置轮播图的文字显示
        mTvTitle.setText(newsCenterTabBean.data.topnews.get(0).title);

        // 给轮播图设置滑动监听
        mViewPager.addOnPageChangeListener(this);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
        mTvTitle.setText(newsCenterTabBean.data.topnews.get(position).title);

        int count = mContainerPoints.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = mContainerPoints.getChildAt(i);
            if (position == i) {
                // 选中的页面
                child.setBackgroundResource(R.drawable.guide_point_red);
            } else {
                // 未选中
                child.setBackgroundResource(R.drawable.guide_point_grey);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }
}
